<template>
  <div id="login" class="animated fadeIn">
    <div id="MainBackgroundArea" class="login_container">
      <div>
        <div class="login_container_form_title">
          <img style="height: 50px;" :src="getServerBg.upPic.sysLabel.pic">
        </div>
        <div
          class="styleWrap"
        >
          <div
            class="login_container_form_img"
          >
            <img style="width:70px;height:70px" :src="getServerBg.upPic.sysLogo.pic">
          </div>
          <el-tabs
            v-model="activeName"
            style="width: 400px;position: absolute;right: 1%;top: 25%;"
            :stretch="true"
            class="tabsStyle"
            @tab-click="handleClick"
          >
            <el-tab-pane label="账号密码登陆" name="first" />
            <el-tab-pane v-if="getServerBg.qrConfig" label="扫码快捷登录" name="second" />
          </el-tabs>
          <div v-if="activeName===&quot;first&quot;">
            <div :class="[isActive]" class="login_container_form">
              <div
                class="loginPage"
              >
                <!-- :style="{
              transform: transFlag === 0 ? 'rotateY(180deg)' : '',
              opacity: transFlag === 1 ? '1' : '0',
              'z-index': transFlag === 1 ? '999' : '-1'
            }" -->
                <!-- <div class="login_title">
            <div style="flex:1"> 账号密码登陆 </div>
            <div style="flex:1;text-align:right">
              <div v-if="getServerBg.qrConfig" class="qrcode" @click="gotoQr">
                <img
                  style="width:22px;height:22px;vertical-align: middle;"
                  src="../../assets/images/login/qrcode.png"
                >
                <span style="vertical-align: middle;">扫码快捷登录</span>
              </div>
            </div>
          </div> -->
                <div class="login_container_form_action">
                  <div>
                    <el-input
                      v-model="form.username"
                      type="text"
                      autofocus
                      clearable
                      placeholder="账户"
                      @blur="getChineseNames"
                    >
                      <i slot="prefix" class="el-input__icon el-icon-user" />
                    </el-input>
                  </div>
                  <div style="margin-top: 15px;">
                    <el-input
                      v-model="form.password"
                      type="password"
                      clearable
                      placeholder="密码"
                      show-password
                      @keyup.enter.native="onSubmit()"
                    >
                      <i slot="prefix" class="el-input__icon el-icon-lock" />
                    </el-input>
                  </div>
                  <div style="margin-top: 15px;">
                    <el-date-picker
                      v-model="year_select"
                      style="width: 100%;"
                      value-format="yyyy"
                      type="year"
                      placeholder="请选择年份生成报表"
                    />
                  </div>
                  <div style="margin-top: 15px;">
                    <el-button
                      type="primary"
                      :loading="isFlag"
                      style="width:95%;margin-left:2%"
                      @click="onSubmit()"
                    >登录
                    </el-button>
                  </div>
                <!-- <div v-if="getServerBg.qrConfig" class="qrcode" @click="gotoQr">
              <img
                style="width:22px;height:22px;vertical-align: middle;"
                src="../../assets/images/login/qrcode.png"
              >
              <span style="vertical-align: middle;">扫码快捷登录</span>
            </div> -->
                </div>
              </div>

            </div>
            <div :class="[isActive1]" class="login_container_second">
              <div class="login_container_second_title" @click="goBack">
                <span>
                  <i class="el-icon-back" />
                </span>
                <span>返回登录</span>
              </div>
              <div class="chooseSystemClass">
                选择你的系统
              </div>
              <div class="login_container_second_detail">
                <div
                  v-for="(item, index) in systemList"
                  :key="index"
                  class="login_container_second_detail_item"
                  @click="chooseSysItem(item)"
                >
                  <!-- <div style="flex:2">
              <img style="width:40px;border-radius:10px" src="../../assets/images/commonPropertypage/fq.png">
            </div> -->
                  <div class="sysName" style="padding-left:10px">
                    {{ item.name }}
                  </div>
                  <div class="sysIcon">
                    <i class=" el-icon-right" />
                  </div>
                </div>
              </div>
            </div>
            <div :class="[isActive2]" class="login_container_second">
              <div class="login_container_second_title" @click="goBack">
                <span>
                  <i class="el-icon-back" />
                </span>
                <span>返回登录</span>
              </div>
              <div class="chooseSystemClass">
                选择你的角色
              </div>
              <div class="login_container_second_detail">
                <div
                  v-for="(item, index) in roleIdList"
                  :key="index"
                  class="login_container_second_detail_item"
                  @click="chooseRole(item)"
                >
                  <div class="sysName" style="padding-left:10px">
                    {{ item.name }}
                  </div>
                  <div class="sysIcon">
                    <i class=" el-icon-right" />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="qrClass">
            <div
              class="qrPage"
            >
              <!-- :style="{
            transform: transFlag === 0 ? 'rotateY(0deg)' : '',
            opacity: transFlag === 0 ? '1' : '0',
            'z-index': transFlag === 0 ? '999' : '-1'
          }" -->
              <div>
                <iframe
                  id="iframeId"
                  :src="iframeSrc"
                  style="height:300px;border:none;width:250px"
                />
              </div>
              <span
                class="account"
                style="vertical-align: middle;"
              >--- 使用浙政钉扫描二维码 ---</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="login_footer" @click="gotoAdminMananger">
      安装包下载
    </div>
    <div class="login_footer_copyright">
      <span>{{ getServerBg.copyright }}</span>
    </div>
    <div class="dialog">
      <el-dialog
        :title="dialogTitle"
        :visible.sync="phoneDialogVisible"
        width="30%"
        :before-close="handleClose"
        :close-on-click-modal="false"
        :show-close="false"
        append-to-body
      >
        <span>手机号码:</span>
        <span>
          <el-input
            v-model="dialogPhone"
            style="width:70%"
            placeholder="请输入手机号码"
          />
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button
            type="primary"
            @click="againSubmit"
          >继续扫码登录</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getName, login, qrLogin } from '@/api/login/index';
import { getBrowserInfo } from '@/utils/commonMethods.js';
import { Message } from 'element-ui';
import { setToken, getToken, removeToken } from '@/utils/auth.js';
import { getGlobal } from '@/utils/global';
import { getMenuList, getUnit } from '@/api/login';
import { mapState } from 'vuex';
import { autoLogin } from './cache';

window.onload = function() {
  if (window !== top) {
    top.location.href = location.href;
  }
};

export default {
  inject: ['reload'],
  data() {
    return {
      activeName: 'first',
      dialogTitle: '',
      dataCode: '',
      phoneDialogVisible: false,
      dialogPhone: '',
      transFlag: 1,
      iframeSrc: '',
      defaultSysLogo: require('@/assets/images/login/loginTitle.png'),
      isActive: '',
      isActive1: '',
      isActive2: '',
      isActive3: '',
      systemList: [],
      homeYear: new Date().getFullYear(),
      roleIdList: [],
      roleName: '',
      arr: [],
      year_select: '',
      isFlag: false,
      dialogVisible: false,
      checked: '',
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          {
            required: true,
            message: '账号不可为空',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不可为空',
            trigger: 'blur'
          }
        ],
        year: [{ required: true, trigger: 'bll' }]
      }
    };
  },
  computed: {
    ...mapState(['getServerBg'])
  },
  mounted() {
    this.$nextTick(() => {
      const year = new Date().getFullYear();
      this.year_select = year.toString();
    });
  },
  created() {
    if (localStorage.getItem('dialogPhone')) {
      setTimeout(() => {
        this.activeName = 'second';
        this.gotoQr();
      }, 1500);
    }
    // 通过addEventListener 绑定的事件会出现多次调用方法的情况
    // window.addEventListener('message', event => {
    //   let data = '';
    //   data = event.data;
    //   this.dataCode = data.code;
    //   if (this.dataCode) {
    //     console.log(this.dataCode);
    //     this.qrLogin();
    //   }
    // });

    window.onmessage = (event) => {
      let data = '';
      data = event.data;
      this.dataCode = data.code;
      if (this.dataCode) {
        console.log(this.dataCode);
        this.qrLogin();
      }
    };
    this.arr = getBrowserInfo();
    const { isAutoLogin } = this.$route.query;
    if (isAutoLogin === '1') {
      autoLogin(this);
    }
  },
  methods: {
    handleClick(tab, event) {
      this.gotoQr();
    },
    async getUnit(id) {
      await getUnit({ userId: id, resultAsTree: true, showBindOnly: true }).then(({ data }) => {
        setToken('userUnitList', JSON.stringify(data));
        setToken('enterpriseCode', data && data[0] && data[0].enterpriseCode);
        setToken('enterpriseName', data && data[0] && data[0].name);
      });
    },
    againSubmit() {
      if (this.dialogPhone === '') {
        Message({
          message: '手机号码不能为空',
          type: 'warning'
        });
      } else {
        this.phoneDialogVisible = false;
        localStorage.setItem('dialogPhone', this.dialogPhone);
        window.location.reload();
        // setTimeout(() => {
        //   this.reload();
        // }, 1000);
      }
    },
    qrLogin() {
      qrLogin({
        appId: localStorage.getItem('appId'),
        code: this.dataCode,
        telephone: localStorage.getItem('dialogPhone')
          ? localStorage.getItem('dialogPhone')
          : ''
      }).then(res => {
        if (res.success) {
          this.getUnit(res.data.id);
          this.dialogPhone = '';
          localStorage.removeItem('dialogPhone');
          setToken('xcNickName', res.data.trueName);
          setToken('chooseYear', this.year_select);
          setToken('avatar', res.data.avatar);
          setToken('avatarId', res.data.avatarId);
          setToken('xcToken', res.token);
          setToken('isShowLoading', '1');
          setToken('xcUserId', res.data.id);
          setToken('enterpriseList', JSON.stringify(res.data.enterprise));
          setToken('enterprise_jc', JSON.stringify(res.data.enterprise_jc));

          if (res.data.roleIdList.length === 0) {
            Message({
              message: '该用户没有配置系统,请联系管理员进行配置',
              type: 'warning'
            });
          } else {
            if (
              res.data.roleIdList.length === 1 &&
              res.data.roleIdList[0].children.length === 1
            ) {
              this.chooseSysItem(res.data.roleIdList[0]);
            } else {
              this.roleName = '';
              this.isActive = 'isNext';
              this.isActive1 = 'isNext1';
              this.systemList = res.data.roleIdList;
            }
          }
        } else {
          this.dialogTitle = res.message + res.detail;
          setTimeout(() => {
            this.phoneDialogVisible = true;
          }, 1000);
        }
      });
    },
    handleClose() {
      this.dialogPhone = '';
      localStorage.removeItem('dialogPhone');
      this.phoneDialogVisible = false;
    },
    gotoQr() {
      this.iframeSrc = `${
        this.getServerBg.qrConfig.qrDomain
      }/oauth2/auth.htm?response_type=code&client_id=${
        this.getServerBg.qrConfig.qrAgentId
      }&redirect_uri=${
        this.getServerBg.qrConfig.qrCallback
      }&scope=get_user_info&authType=QRCODE&embedMode=true`;
      this.transFlag = 0;
    },
    gotoBack() {
      this.iframeSrc = '';
      this.transFlag = 1;
      this.dialogPhone = '';
      localStorage.removeItem('dialogPhone');
    },
    goBack() {
      this.transFlag = 1;
      this.systemList = [];
      this.roleIdList = [];
      this.isActive = 'isBack';
      this.isActive1 = 'isBack1';
      this.isActive2 = 'isBack1';
      removeToken('sysitemId');
      removeToken('sysitemName');
      removeToken('roleList');
    },
    getChineseNames() {
      getName({
        username: this.form.username
      }).then(res => {
        if (res.success) {
          setToken('username', this.form.username);
          setToken('phone', this.form.username);
          this.form.username = res.data;
        } else {
          setToken('username', '');
        }
      });
    },
    onSubmit() {
      if (this.form.username === '' || this.form.password === '') {
        Message({
          message: '账号或者密码不能为空',
          type: 'warning'
        });
      } else if (this.year_select === '' || this.year_select === null) {
        Message({
          message: '请选择一个年份',
          type: 'warning'
        });
      } else if (!getToken('username')) {
        Message({
          message: '账号不存在',
          type: 'warning'
        });
      } else {
        this.isFlag = true;
        login({
          password: this.form.password.trim(),
          username: getToken('username').trim(),
          year: new Date().getFullYear(),
          name: getToken('username'),
          appId: getToken('appId'),
          browser: this.arr[1],
          operateSystem: this.arr[0]
        }).then(res => {
          this.isFlag = false;
          if (res.success) {
            this.getUnit(res.data.id);
            setToken('xcNickName', res.data.trueName);
            setToken('chooseYear', this.year_select);
            setToken('avatar', res.data.avatar);
            setToken('avatarId', res.data.avatarId);
            setToken('xcToken', res.token);
            setToken('isShowLoading', '1');
            setToken('xcUserId', res.data.id);
            setToken('enterpriseList', JSON.stringify(res.data.enterprise));
            setToken('enterprise_jc', JSON.stringify(res.data.enterprise_jc));

            if (res.data.roleIdList.length === 0) {
              Message({
                message: '该用户没有配置系统,请联系管理员进行配置',
                type: 'warning'
              });
            } else {
              if (
                res.data.roleIdList.length === 1 &&
                res.data.roleIdList[0].children.length === 1
              ) {
                this.chooseSysItem(res.data.roleIdList[0]);
              } else {
                this.roleName = '';
                this.isActive = 'isNext';
                this.isActive1 = 'isNext1';
                this.systemList = res.data.roleIdList;
              }
            }
          } else {
            Message({
              type: 'warning',
              message: res.message + res.detail
            });
          }
        });
      }
    },
    gotoAdminMananger() {
      getGlobal().then(all => {
        const a1 = `http://${all.url.split('/')[2]}/adminManager`;
        const tempwindow = window.open('_blank');
        tempwindow.location = a1;
      });
    },
    chooseRole(item) {
      setToken('xcRoleId', item.id);
      setToken('xcRoleName', item.name);
      setToken('isCanGoto', 'isCanGoto');
      const loading = this.$loading({
        lock: true,
        text: '正在登录...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(async() => {
        loading.close();
        if (item.pcUrlName !== '') {
          let params = {};
          if (item.pcUrlName === '/layoutContainer') {
            let origtinMenuId = '';
            let origtinMenuTitle = '';
            await getMenuList({
              roleId: getToken('xcRoleId'),
              state: 4,
              url: '',
              appId: getToken('sysitemId'),
              isMeta: true
            }).then(res => {
              if (res.success) {
                if (res.data[0].children.length !== 0) {
                  // if (getToken('sysitemName') === '浙里药店管理平台') {
                  //   res.data[0].children[0].children.map(o => {
                  //     if (o.path === res.data[0].redirect) {
                  //       origtinMenuId = o.id;
                  //       origtinMenuTitle = o.title;
                  //     }
                  //   });
                  // } else {
                  res.data[0].children.map(o => {
                    if (o.path === res.data[0].redirect) {
                      origtinMenuId = o.id;
                      origtinMenuTitle = o.title;
                    }
                  });
                  // }
                }
              }
            });
            params = {
              isHideLeft: '1',
              isHideTop: '1',
              menuId: origtinMenuId,
              title: origtinMenuTitle
            };
          } else {
            params = {
              isHideLeft: '1',
              isHideTop: '1'
            };
          }
          setTimeout(() => {
            if (getToken('sysitemName') === '浙里药店管理平台') {
              this.$router.push({
                path: '/yaoantongBigScreen'
              });
            } else {
              this.$router.push({
                path: item.pcUrlName,
                query: params
              });
            }
          }, 500);

          setToken('pcUrlName', item.pcUrlName);
          setToken('pcUrl', item.pcUrl);
        } else {
          this.$message.warning('抱歉，此角色无权限进入');
        }
      }, 800);
    },
    chooseSysItem(item) {
      if (item.children.length === 0) {
        Message({
          message: '该用户没有该系统的角色,请联系管理员进行配置',
          type: 'warning'
        });
      } else {
        const { id } = item;
        this.$store.dispatch('getServerBg/changeUppic', id);
        if (item.children.length === 1) {
          this.chooseRole(item.children[0]);
        } else {
          this.isActive1 = 'isNext2';
          this.isActive2 = 'isNext1';
          this.roleIdList = item.children;
          setToken('roleList', JSON.stringify(item.children));
        }
        setToken('sysitemId', item.id);
        setToken('sysitemName', item.name);
      }
    }
  }
};
</script>
<style lang="scss" scoped vars="{ color }">
.isNext {
  animation: mymove 1s ease-in-out 0s 1 alternate forwards;
}
@keyframes mymove {
  from {
    right: 5%;
    opacity: 1;
    visibility: visible;
  }
  to {
    right: 20%;
    opacity: 0;
    visibility: hidden;
  }
}
.isBack {
  animation: mymove1 1s ease-in-out 0s 1 alternate forwards;
}
@keyframes mymove1 {
  from {
    right: 20%;
    opacity: 0;
    visibility: hidden;
  }
  to {
    right: 5%;
    opacity: 1;
    visibility: visible;
  }
}

.isNext1 {
  animation: mymove2 1s ease-in-out 0s 1 alternate forwards;
}
@keyframes mymove2 {
  from {
    right: -19%;
    opacity: 0;
    visibility: hidden;
  }
  to {
    right: 5%;
    opacity: 1;
    visibility: visible;
  }
}
.isBack1 {
  animation: mymove3 1s ease-in-out 0s 1 alternate forwards;
}
@keyframes mymove3 {
  from {
    right: 5%;
    opacity: 1;
    visibility: visible;
  }
  to {
    right: -19%;
    opacity: 0;
    visibility: hidden;
  }
}

.isNext2 {
  animation: mymove4 1s ease-in-out 0s 1 alternate forwards;
}
@keyframes mymove4 {
  from {
    right: 5%;
    opacity: 1;
    visibility: visible;
  }
  to {
    right: 19%;
    opacity: 0;
    visibility: hidden;
  }
}

.login_footer {
  position: absolute;
  bottom: 5px;
  text-align: center;
  color: #1890ff;
  font-size: 1rem;
  width: 125px;
  height: 35px;
  line-height: 35px;
  opacity: 1;
  background: rgba(216, 216, 216, 0);
  border: 1px solid #1890ff;
  border-radius: 23px;
  right: 3%;
  bottom: 2%;
  z-index: 99;
  &:hover {
    text-decoration: underline;
    cursor: pointer;
  }
}
.login_footer_copyright {
  position: absolute;
  bottom: 5px;
  width: 100%;
  text-align: center;
  font-size: 1rem;
  height: 35px;
  line-height: 35px;
  opacity: 1;
  bottom: 2%;
  & > span:hover {
    cursor: pointer;
  }
}
.login_container_title {
  margin-top: 1rem;
  margin-bottom: 1rem;
}
.login_container_form {
  width: 360px;
  position: absolute;
  top: 40%;
  right: 6%;
}
.login_container {
  width: 100%;
  height: calc(100vh);
  padding: 10px;
  text-align: center;
  background-size: cover;
  overflow-x: hidden;
}
.login_container_form_action {
  margin-top: 10px;
}

.login_container_form_action /deep/ .el-input__inner {
  border: none;
  background: #fff;
  border-radius: 0px;
  font-size: 16px;
  margin-left: 5px;
  border-bottom: 1px solid #e2e2e2;
}
.login_container_form_action /deep/ .el-input__icon {
  height: 100%;
  width: 25px;
  text-align: center;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
  line-height: 40px;
  font-size: 20px;
  color: #1890ff;
}

.login_form /deep/ .el-form-item__label {
  width: 70px !important;
  text-align: right;
}
.login_form /deep/ .el-input {
  width: 85% !important;
}
.login_form /deep/ .el-form-item__content {
  margin-left: 70px !important;
}
.login_container_second {
  width: 360px;
  position: fixed;
  top: 40%;
  right: -19%;
  text-align: left;
  opacity: 0;
  .login_container_second_title {
    font-size: 16px;
    color: gray;
    font-weight: bolder;
  }
  .login_container_second_title:hover {
    cursor: pointer;
    text-decoration: underline;
  }
  .chooseSystemClass {
    font-size: 14px;
    font-family: PingFangSC, PingFangSC-Medium;
    font-weight: 500;
    text-align: left;
    color: #1890ff;
    margin-top: 5px;
  }
  .login_container_second_detail {
    margin-top: 5px;
    height: 260px;
    padding: 5px;
    overflow-y: auto;
    padding: 5px;
    .login_container_second_detail_item {
      // height: 55px;
      opacity: 1;
      background: #d8d8d8;
      border-radius: 10px;
      display: flex;
      padding: 5px;
      margin-bottom: 10px;
      .sysName {
        font-size: 14px;
        font-family: PingFangSC, PingFangSC-Medium;
        font-weight: bold;
        text-align: left;
        color: #333333;
        flex: 10;
        line-height: 40px;
      }
      .sysIcon {
        flex: 1;
        font-size: 16px;
        color: gray;
        font-weight: bolder;
        text-align: center;
        line-height: 37px;
      }
    }
    .login_container_second_detail_item:hover {
      cursor: pointer;
      background: #1890ff;
      color: #fff !important;
    }
  }
}
.login_container_form_title {
  text-align: left;
  padding-left: 50px;
  margin-top: 30px;
}
.login_title {
  height: 22px;
  opacity: 1;
  font-size: 15px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  text-align: left;
  color: #1890ff;
  line-height: 22px;
  margin-bottom: 10px;
  margin-top: 15px;
  display: flex
}
.qrcode {
  font-family: PingFangSC, PingFangSC-Medium;
  color: #1890ff;
}
.qrcode:hover {
  text-decoration: underline;
  cursor: pointer;
}
.loginPage {
  background-repeat: no-repeat;
  background-position: center center;
  backface-visibility: hidden;
  transition: 2s;
  z-index: 999;
}
.qrPage {
  width: 100%;
  // transform: rotateY(-180deg);
  // position: absolute;
  // top: 120px;
  // left: 0px;
  // backface-visibility: hidden;
  // transition: 2s;
  z-index: -1;
}
.account {
  text-align: center;
  font-size: 12px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  color: gray;
  display: inline-block;
  margin-top: 10px;
}
.account:hover {
  cursor: pointer;
  text-decoration: underline;
}
.login_container_form_img{
  position: absolute;
  top: 5%;
  right: 40%;
}

 .tabsStyle /deep/ .el-tabs__nav-wrap::after {
    content: "";
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 2px;
    background-color: #dfe4ed00;
    z-index: 1;
}
.qrClass{
    width: 360px;
    position: absolute;
    top: 36%;
    right: 4%;
}
.styleWrap{
  position: absolute;
    width: 420px;
    height: 480px;
    right: 2%;
    top: 17%;
    background-color: #fff;
    border-radius: 10px;
}

</style>
